<template>
	<view class="c-user">
		<view class="nav" :style="{height:h}">
			<view class="n-sub">
				<text>消息</text>
				<navigator :url="url">
					<view class="w-box-area-add-btn">+</view>
				</navigator>
			</view>
		</view>
		<view class="c-user-nav" :style="{top:h2}">
			<view class="nav-item">
				<image src="@/static/images/icons/sml/icon-sml-calendar.png" mode="widthFix"></image>
				<text>日历</text>
			</view>
			<view class="nav-item" @click="onNavTo(null,1)">
				<image src="@/static/images/icons/sml/icon-sml-tolist.png" mode="widthFix"></image>
				<text>待办</text>
				<text class="nav-item-sum" v-show="itemSum!=0">{{itemSum}}</text>
			</view>
			<view class="nav-item">
				<image src="@/static/images/icons/sml/icon-sml-ding.png" mode="widthFix"></image>
				<text>DING</text>
			</view>
		</view>
		<view class="c-user-lists" :style="{marginTop:h3}">
			<view class="c-user-list" v-for="(item,index) in items" :key="index" @click="onNavTo(item,0)">
				<view class="c-user-img">
					{{_retSlgName(item.fromUserName)}}
				</view>
				<view class="c-user-info">
					<view class="c-user-top">
						<view class="c-user-name">
							{{item.fromUserName}}
						</view>
						<view class="c-user-time">
							{{_retFormatDate(item.lastChatTime.substr(0,19))}}
						</view>
					</view>
					<view class="c-user-content">
						<view class="c-user-cont">
							{{item.lastCont}}
						</view>
						<view class="c-user-sum" v-show="item.unreadCount>0">
							{{item.unreadCount}}
						</view>
					</view>
				</view>
			</view>
			<view class="c-user-list" v-show="items.length==0">
				{{errorTip}}
			</view>
		</view>
	</view>
</template>
<script>
	let pageApp = getApp();
	export default {
		data() {
			return {
				items: [],
				h: "0px",
				h2: "0px",
				h3: "0px",
				itemSum:0,
				errorTip: "正在加载数据...",
				url: "./MsgSearchUser?source=msglist"
			}
		},
		onShow: function() {

			// 发送聊天好友信息请求
			this.sendInitMsg("0");

			// 计算总数量
			let strCountSun = this.chat.countSum().toString();
			if (strCountSun == "0") {
				// 隐藏导航栏显示
				uni.removeTabBarBadge({
					index: 0
				})
			} else {
				// 设置导航栏显示
				uni.setTabBarBadge({
					index: 0,
					text: strCountSun
				})
			}
		},
		onLoad: function() {
			// console.log("1.进入");
			
			// 获取待办总数量
			this.getToDoList();
			
			// 获取导航条高度
			uni.getSystemInfo({
				success: (res) => {
					this.h = res.statusBarHeight + 50 + "px";
					this.h2 = this.h;	
					this.h3 = res.statusBarHeight + 110 + "px";
				}
			})

			// 发起连接请求
			this.connWs();

			// #ifndef APP-PLUS
			this.ws.addEventListener("close", res => {
				// console.log("4.close");
				// 关闭连接
				this.ws.close();
			})
			// #endif

			// #ifdef APP-PLUS
			this.ws.onClose(res => {
				// console.log("4.close");
				// 关闭连接
				this.ws.close();
			})
			// #endif

			// #ifndef APP-PLUS
			this.ws.addEventListener("error", res => {
				// console.log("5.error");
				uni.showToast({
					icon: "none",
					title: "断网了，请稍后再试！",
					success: () => {
						// 发起连接请求
						this.connWs();
					}
				})
			})
			// #endif

			// #ifdef APP-PLUS
			this.ws.onError(res => {
				// console.log("5.error");
				uni.showToast({
					icon: "none",
					title: "断网了，请稍后再试！",
					success: () => {
						// 发起连接请求
						this.connWs();
					}
				})
			})
			// #endif

			// 请求
			this.getInitMsgUserList();
		},
		methods: {
			_retSlgName(v) {
				return (v) ? v.substr(0, 1) : "";
			},
			_retFormatDate(v) {
				return (v) ? this.retFormatDate(v) : "";
			},
			onNavTo(item, type) {
				switch (type) {
					case 0:
						uni.setStorageSync("fromUserName", item.fromUserName);
						uni.navigateTo({
							url: "./MsgList?ConnUserId=" + item.uid
						})
						break;
					case 1:
						uni.navigateTo({
							url: "../../system/Todo/TodoList"
						})
						break;
				}

			},
			openWs() {
				// #ifndef APP-PLUS
				this.ws.addEventListener("open", res => {
					// console.log("2.open");
					// 发送聊天好友信息请求
					this.sendInitMsg("0");
					// 发送心跳
					this.heartBeat();
				})
				// #endif

				// #ifdef APP-PLUS
				this.ws.onOpen(res => {
					// console.log("2.open");
					// 发送聊天好友信息请求
					this.sendInitMsg("0");
					// 发送心跳
					this.heartBeat();
				})
				// #endif

				// #ifndef APP-PLUS
				this.ws.addEventListener("message", res => {
					//console.log("3.响应", res.data);
					this.getMessageList(res.data);
				})
				// #endif

				// #ifdef APP-PLUS
				this.ws.onMessage(res => {
					//console.log("3.响应", res.data);
					this.getMessageList(res.data);
				})
				// #endif
			},
			connWs() {
				// #ifndef APP-PLUS
				try {
					if (this.ws) this.ws.close();
					this.ws = new WebSocket(pageApp.globalData.ws + "/MsgService/" + uni.getStorageSync("token"));
					this.chat.createWs(this.ws);
				} catch (e) {
					console.log("error", e.Message);
				}
				// #endif

				// #ifdef APP-PLUS
				try {
					if (this.ws) this.ws.close();
					this.ws = uni.connectSocket({
						url: pageApp.globalData.ws + "/MsgService/" + uni.getStorageSync("token"),
						success: () => {
							this.chat.createWs(this.ws);
						}
					})
				} catch (e) {
					console.log("error", e.Message);
				}
				// #endif
				this.openWs();
			},
			getInitMsgUserList() {
				if (uni.getStorageSync("msgUserList")) {
					this.items = JSON.parse(uni.getStorageSync("msgUserList"));
				} else {
					this.errorTip = "你还没有聊天的用户！"
				}
				if (uni.getStorageSync("msgList")) {
					this.chat.createMsgList(JSON.parse(uni.getStorageSync("msgList")));
				}
			},
			sendInitMsg(n) {
				if (this.ws && this.ws.readyState == 1) {
					let _newData = JSON.stringify({
						"msgtype": n
					})

					// #ifndef APP-PLUS
					this.ws.send(_newData);
					// #endif

					// #ifdef APP-PLUS
					this.chat.ws.send({
						data: _newData
					})
					// #endif
				}
			},
			heartBeat() {
				if (wsTask) clearInterval(wsTask);
				let n = 0;
				let wsTask = setInterval(() => {
					n++;
					// console.log("次数" + n)
					// 发送心跳请求
					this.sendInitMsg("1");
				}, 30000)
			},
			recWsMsg(_res) {
				// 增加未读总量
				this.chat.addCount(_res.fromid);
				// 增加最后一条内容
				this.chat.addMsg(_res.fromid, _res.content);
				// 计算总数量
				let strCountSun = this.chat.countSum().toString();
				// 设置导航栏显示
				uni.setTabBarBadge({
					index: 0,
					text: strCountSun
				})
				// 如果原来有数据;
				if (uni.getStorageSync("msgList")) { // 有数据
					// 生成新对象
					let _newMsgList = JSON.parse(uni.getStorageSync("msgList"));
					// 添加新数据
					_newMsgList.push(_res);
					// 保存全局对话数据
					this.chat.createMsgList(_newMsgList);
					// 添加并保存
					uni.setStorageSync("msgList", JSON.stringify(_newMsgList))
				} else {
					// 自定义一个数组
					let __res = [];
					// 添加消息内容
					__res.push(_res);
					// 保存全局对话数据
					this.chat.createMsgList(__res);
					// 新建保存
					uni.setStorageSync("msgList", JSON.stringify(__res))
				}
			},
			getMsgUserList(res) {
				// 过滤自己和为空记录
				this.msguserlist = res.data.filter((item, index) => {
					return (item.fromUserName) && (item.uid != JSON.parse(uni.getStorageSync("userLoginData")).UserID)
				})
				// 添加全局对象
				this.chat.createMsgUserList(this.msguserlist);
				// 是否读取过
				if (uni.getStorageSync("msgUserList")) {
					// 本地数据转成对象
					let _msgUserList = JSON.parse(uni.getStorageSync("msgUserList"));
					// 比较两次数据内容
					this.msguserlist.forEach(item => {
						// 查询uid是否不同
						let blnUid = _msgUserList.find(obj => obj.uid == item.uid);
						// 如果有不同
						if (!blnUid) {
							// 新增加对象
							_msgUserList.push(item);
						}
					})
					// 添加全局对象
					this.chat.createMsgUserList(_msgUserList);
					// 显示列表
					this.items = _msgUserList;
					// 重新保存
					uni.setStorageSync("msgUserList", JSON.stringify(_msgUserList));
				} else {
					// 添加全局对象
					this.chat.createMsgUserList(this.msguserlist);
					// 显示列表
					this.items = this.msguserlist;
					// 重新保存
					uni.setStorageSync("msgUserList", JSON.stringify(this.msguserlist));
				}
			},
			getMessageList(res) {
				if (res) {
					// 转成对象
					let _res = JSON.parse(res)
					switch (_res.code) {
						case 0: //聊天用户
							// console.log("3-0 首次响应");
							this.getMsgUserList(_res);
							break;
						case 1:
							// console.log("3-1 心跳响应")
							break;
						case 3:
							if (_res.data) {
								// console.log("3-2 离线数据");
								_res.data.forEach((item, index) => {
									this.recWsMsg(item);
								})
							} else {
								// console.log("3-3 推送响应");
								this.recWsMsg(_res);
							}
							break;
					}
				}
			},
			getToDoList() {
				let apiData = {
					url: pageApp.globalData.url + "/ToDoListList",
					success: (d) => {
						// console.log(d)
						this.itemSum = d.data.records;
						if(this.itemSum>99){
							this.itemSum = "99+"
						}
					}
				}
				// 发送数据请求
				this.vjAjaxData(apiData);
			}
		}
	}
</script>
<style>
	page {
		background-color: #F1F5F6;
	}

	.c-user {
		padding: 0 40rpx;
		background-color: #FFFFFF;
	}

	.c-user-nav {
		display: flex;
		position: fixed;
		align-items: center;
		left: 0;
		z-index: 9;
		width: 100%;
		background-color: #FFFFFF;
		height: 100rpx;
	}

	.c-user-nav .nav-item {
		width: 33%;
		display: flex;
		justify-content: center;
	}

	.c-user-nav .nav-item image {
		margin: 10rpx 8rpx 0 0;
		width: 32rpx;
	}

	.c-user-nav .nav-item text {
		font-size: 28rpx;
		color: #707070;
	}

	.c-user-nav .nav-item .nav-item-sum {
		font-size: 20rpx;
		margin: 10rpx 0 0 8rpx;
		background-color: red;
		color: #ffffff;
		padding: 8rpx;
		max-width: 40rpx;
		min-height: 20rpx;
		text-align: center;
		line-height: 20rpx;
		height: 20rpx;
		border-radius: 50%;
	}

	.n-sub {
		margin-top: 20rpx;
		justify-content: center;
	}

	.n-sub text {
		font-size: 32rpx;
		font-weight: 700;
		color: #000000;
	}

	.n-sub navigator {
		position: absolute;
		right: 10rpx;
	}

	.c-user-list {
		display: flex;
		position: relative;
		width: 100%;
		padding: 20rpx 0;
		border-bottom: solid 2rpx #F1F5F6;
	}

	.w-box-area-add-btn {
		width: 55rpx;
		text-align: center;
		font-size: 50rpx;
		height: 55rpx;
		background-color: #4497e1;
		color: #fff;
		border-radius: 50%;
	}

	.c-user-img {
		background-color: #4497e1;
		border-radius: 16rpx;
		color: #ffffff;
		text-align: center;
		width: 80rpx;
		font-size: 36rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.c-user-info {
		margin-left: 20rpx;
	}

	.c-user-top {
		display: flex;
	}

	.c-user-name {
		font-size: 34rpx;
		line-height: 38rpx;
		color: #000000;
	}

	.c-user-content {
		font-size: 26rpx;
		line-height: 46rpx;
		color: #707070;
	}

	.c-user-cont {
		overflow: hidden;
		display: inline-block;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 420rpx;
	}

	.c-user-time {
		position: absolute;
		right: 0;
		font-size: 26rpx;
		color: #707070;
	}

	.c-user-content {
		display: flex;
	}

	.c-user-sum {
		position: absolute;
		margin-top: 10rpx;
		right: 0;
		font-size: 20rpx;
		background-color: red;
		color: #ffffff;
		padding: 8rpx;
		min-width: 20rpx;
		min-height: 20rpx;
		text-align: center;
		line-height: 20rpx;
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
	}
</style>
